<?php

require_once('../include/GeneralTop.php');
require('../include/class/db.php');

$db = new db;

if (!$pay_member) {
	die('<div style="text-align:center">Permission denied...</div>');
}
if(MEMBER_PAID === (int)$_SESSION['MM_UserGroup']) {
	$pid = isset($_GET['PId']) ? $_GET['PId'] : $_POST['PId'];
	$check_sql = "select add_user from petlostfound where PId=".$pid;
	$check_sql_query = $db->query($check_sql);
	$check_sql_row = $db->fetch($check_sql_query);
	if((int)$check_sql_row['add_user'] !== (int)$_SESSION['MM_Username_id']){
		die('<div style="text-align:center">You have no permission to edit this pet...</div>');
	}
}

if ((isset($_POST["submit"]))) {
    //handle pics
    /*********************BEGIN*************************/
    $sub_folder = date("Y-m-d");	
	$savePath = IMAGES_PET_SAVE_FOLDER.'/'.$sub_folder;
	if(!is_dir($savePath)) {
		mkdir($savePath, 0755);
	}
    
    $fileTemp1 = getimagesize($_FILES['pic1']['tmp_name']);
	$trueType1 = $fileTemp1['mime'];
	$fileTemp2 = getimagesize($_FILES['pic2']['tmp_name']);
	$trueType2 = $fileTemp2['mime'];
	$fileTemp3 = getimagesize($_FILES['pic3']['tmp_name']);
	$trueType3 = $fileTemp3['mime'];
	$fileSizeAll1 = $_FILES['pic1']['size'];
	$fileSizeAll2 = $_FILES['pic2']['size'];
	$fileSizeAll3 = $_FILES['pic3']['size'];
	if('' != $_FILES['pic1']['name']) {
		if(!in_array($trueType1, $typeArray)) {
			echo '<div align="center">The format of the pics you uploaded is not png,jpg,jpeg,gif, please upload again</div>';
			die();
		}
		if($fileSizeAll1 > $pic_size_limit * 1024) {
			echo '<div align="center">The size of the pics you uploaded exceed limitation, please upload another one</div>';
			die();
		}
		//first pic
		$fileId = md5($_FILES["pic1"]["tmp_name"] + rand()*100000);
		$imagePathInfo = pathinfo($_FILES['pic1']['name']);
		$extension = $imagePathInfo['extension'];
		$imageName = $fileId;
		$imageFullName = $savePath.'/'.$imageName.'.'.$extension;
		$file_name1 = '/'.$sub_folder.'/'.$imageName.'.'.$extension;
		move_uploaded_file($_FILES['pic1']['tmp_name'], $imageFullName);
		
		//generate thumb of first pic
		$imageName_t = $fileId.'_t';
		$imageFullName_t = $savePath.'/'.$imageName_t.'.'.$extension;
		$file_name1_t = '/'.$sub_folder.'/'.$imageName_t.'.'.$extension;
		generateImages($trueType1, $imageFullName, PIC_THUMB_WIDTH, PIC_THUMB_HEIGHT, $imageFullName_t);
		
		$update_pic1 = true;
	}
	else {
		$update_pic1 = false;
	}
	if('' != $_FILES['pic2']['name']) {
		if(!in_array($trueType2, $typeArray)) {
			echo '<div align="center">The format of the pics you uploaded is not png,jpg,jpeg,gif, please upload again</div>';
			die();
		}
		if($fileSizeAll2 > $pic_size_limit * 1024) {
			echo '<div align="center">The size of the pics you uploaded exceed limitation, please upload another one</div>';
			die();
		}
		//second pic
		$fileId = md5($_FILES["pic2"]["tmp_name"] + rand()*100000);
		$imagePathInfo = pathinfo($_FILES['pic2']['name']);
		$extension = $imagePathInfo['extension'];
		$imageName = $fileId;
		$imageFullName = $savePath.'/'.$imageName.'.'.$extension;
		$file_name2 = '/'.$sub_folder.'/'.$imageName.'.'.$extension;
		move_uploaded_file($_FILES['pic2']['tmp_name'], $imageFullName);
		$update_pic2 = true;
	}
	else {
		$update_pic2 = false;
	}
	if('' != $_FILES['pic3']['name']) {
		if(!in_array($trueType3, $typeArray)) {
			echo '<div align="center">The format of the pics you uploaded is not png,jpg,jpeg,gif, please upload again</div>';
			die();
		}
		if($fileSizeAll3 > $pic_size_limit * 1024) {
			echo '<div align="center">The size of the pics you uploaded exceed limitation, please upload another one</div>';
			die();
		}
		//third pic
		$fileId = md5($_FILES["pic3"]["tmp_name"] + rand()*100000);
		$imagePathInfo = pathinfo($_FILES['pic3']['name']);
		$extension = $imagePathInfo['extension'];
		$imageName = $fileId;
		$imageFullName = $savePath.'/'.$imageName.'.'.$extension;
		$file_name3 = '/'.$sub_folder.'/'.$imageName.'.'.$extension;
		move_uploaded_file($_FILES['pic3']['tmp_name'], $imageFullName);
		$update_pic3 = true;
	}
	else {
		$update_pic3 = false;
	}

	/*********************END**************************/
    
    
    $updateSQL = sprintf("UPDATE petlostfound SET PType=%s, PVariety=%s, PGender=%s, 
								PPlace=%s, PIsLost=%s, PDescription=%s, PDate=%s WHERE PId=%s",
                       GetSQLValueString($_POST['type'], "text"),
                       GetSQLValueString($_POST['PVariety'], "text"),
                       GetSQLValueString($_POST['pet_sex'], "text"),
                       GetSQLValueString($_POST['place'], "text"),
                       GetSQLValueString($_POST['PIsLost'], "text"),
                       GetSQLValueString($_POST['desc'], "text"),
                       GetSQLValueString($_POST['find_date'], "text"),
                       GetSQLValueString($_POST['PId'], "int"));
    $db->query($updateSQL);

    if($update_pic1) {
	    $update_pic1_sql = sprintf("UPDATE petlostfound SET PPhoto=%s, PPhoto_thumb=%s
									 WHERE PId=%s",
	                       GetSQLValueString($file_name1, "text"),
	                       GetSQLValueString($file_name1_t, "text"),
	                       GetSQLValueString($_POST['PId'], "int"));
	    $db->query($update_pic1_sql);
    }
    if($update_pic2) {
	    $update_pic2_sql = sprintf("UPDATE petlostfound SET PPhoto2=%s 
									 WHERE PId=%s",
	                       GetSQLValueString($file_name2, "text"),
	                       GetSQLValueString($_POST['PId'], "int"));
	    $db->query($update_pic2_sql);
    }
    if($update_pic3) {
	    $update_pic3_sql = sprintf("UPDATE petlostfound SET PPhoto3=%s 
									 WHERE PId=%s",
	                       GetSQLValueString($file_name3, "text"),
	                       GetSQLValueString($_POST['PId'], "int"));
	    $db->query($update_pic3_sql);
    }
    
    //header("location:".$_SERVER['PHP_SELF']."?result=suc&PId=".$_POST['PId']);
    echo '<script>window.location.href="'.$_SERVER['PHP_SELF'].'?result=suc&PId='.$_POST['PId'].'";</script>';
    exit();
}

$id = "-1";
if (isset($_GET['PId'])) {
    $id = $_GET['PId'];
}

$sql = sprintf("SELECT * FROM petlostfound WHERE PId = %s", GetSQLValueString($id, "int"));
$res = $db->query($sql);
$row = $db->fetch($res);

include('AdminPanel.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="../include/js/calendar.js" type="text/javascript"></script>
</head>

<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post" name="form1" id="form1">
  <table align="center">
    <?php
    if($_GET['result'] && 'suc' == $_GET['result']) {
    ?>
    <tr valign="baseline">
      <td colspan="2" nowrap="nowrap" align="center"><font color="green">更新成功...</font></td>
    </tr>
    <?php
    }
    ?>
    <?php
    if(2 === (int)$row['PType']) {
    	$select2 = 'selected';
    	$select1 = '';
    	$select3 = '';
    }
    else if(1 === (int)$row['PType']) {
    	$select2 = '';
    	$select1 = 'selected';
    	$select3 = '';
    }
    else {
    	$select2 = '';
    	$select1 = '';
    	$select3 = 'selected';
    }
    ?>
    <tr>
      <td scope="row" align="right">分类:</td>
      <td><select name="type">
        <option value="2" <?php echo $select2?>>猫</option>
        <option value="1" <?php echo $select1?>>狗</option>
        <option value="3" <?php echo $select3?>>其他</option> 
      </select></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right" valign="top">品种:</td>
      <td><input type="text" name="PVariety" value="<?php echo $row['PVariety']?>" size="32" /></td>
    </tr>
    <?php
    if(1 === (int)$row['PGender']) {
    	$check1 = 'checked';
    	$check2 = '';
    }
    else if(2 === (int)$row['PGender']) {
    	$check1 = '';
    	$check2 = 'checked';
    }
    ?>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">性别:</td>
      <td>
		<input type="radio" name="pet_sex" value="1" <?php echo $check1?>> 雄 
		<input type="radio" name="pet_sex" value="2" <?php echo $check2?>> 雌 
	  </td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">照片:<br>(不传就是不修改)</td>
      <td><input type="file" name="pic1" /> (列表页图，会自动生成缩略图)<br><input type="file" name="pic2" /><br><input type="file" name="pic3" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right" valign="top">捡到/走失地点:</td>
      <td><input type="text" name="place" value="<?php echo $row['PPlace']?>" size="32" /></td>
    </tr>
    <?php
    if(1 === (int)$row['PIsLost']) {
    	$select1 = 'selected';
    	$select2 = '';
    }
    else if(2 === (int)$row['PIsLost']) {
    	$select1 = '';
    	$select2 = 'selected';
    }
    ?>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right" valign="top">捡到/走失:</td>
      <td>
      	<select name="PIsLost">
          <option value="1" <?php echo $select1?>>找寻失宠</option>
          <option value="2" <?php echo $select2?>>失宠招领</option>       
      	</select>
      </td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right" valign="top">详细信息:</td>
      <td><textarea name="desc" rows="5" cols="30"><?php echo $row['PDescription']?></textarea></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right" valign="top">捡到/走失日期:</td>
      <td>
      	<input type="text" name="find_date" id="find_date" value="<?php echo $row['PDate']?>" size="32" />
      	<img src="../images/calendar.ico" width="25" height="25" onclick="fPopCalendar(event,this,document.getElementById('find_date'))" style="cursor:pointer;">
      </td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">&nbsp;</td>
      <td>
      	<input type="submit" id="submit" name="submit" value="Update record" />&nbsp;&nbsp;
        <input type="button" id="button" onclick="window.location.href='ShowPetLostFoundInfo.php'" value="Back">
      </td>
    </tr>
  </table>
  <input type="hidden" name="PId" value="<?php echo $row['PId']; ?>" />
</form>
<p>&nbsp;</p>
</body>
</html>